<!--  -->
<template>

  <el-dialog title="提示" :visible.sync="dialogVisible" :append-to-body="true" width="300px" class="wx-login" @close="handleColse">

    <div slot="title" class="dialog-header">
      <p v-if="$route.path === '/login'" class="webfont-Bold">微信登录</p>
      <p v-else class="webfont-Bold">微信绑定</p>
    </div>
    <div class="Code">
      <div>
        <wxlogin v-if="redirect_uri" class="Codelogin" :appid="appid" :scope="scope" :href="href" :redirect_uri="redirect_uri" :state="state"/>
        <img v-else :src="imgUrl" alt="" style="width:170px; height:170px;margin-left:40px;cursor: pointer;" @click="clickTest()"/>
      </div>

      <div class="line-box">
        <div class="line-info">
          <span v-for="item in 16" />
        </div>
      </div>

      <div v-if="$route.name === 'login'" class="wx-tips webfont-Bold" style="margin-bottom: 24px;">打开微信扫一扫，授权后即可登录</div>
      <div v-else class="wx-tips webfont-Bold">打开微信扫一扫，授权后即可绑定</div>
    </div>
  </el-dialog>

</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import wxlogin from 'vue-wxlogin'
import {
  setToken
} from '@/utils/auth.js'
import {
  getDefultPath
} from '@/utils/index.js'
import {weixinURL,  isBindWeixin} from '@/api/user.js'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    wxlogin
  },
  props: {
    cdshow: {
      type: Number,
      required: true,
      default: function() {
        return 0
      }
    },
    wxShow: {
      type: Boolean,
      default: false
    },
    number:{
      type: Number
    }
  },
  data() {
    // 这里存放数据
    return {
      dialogVisible: false,
      imgUrl: require('@/assets/images/weima.png'),
      bgImg: require('@/assets/images/login/wx-bg.png'),
      appid: process.env.NODE_ENV === 'development'? 'wxfc738d973e48bbcb':'wx473f72d23dcdf302',
      scope: 'snsapi_login',
      grant_type: 'authorization_code',
      redirect_uri: '',
      character: '',
      state: '',
      time: '',
      numbers: 0,
      href: 'data:text/css;base64,ICAuaW1wb3dlckJveCAucXJjb2RlIHsKICB3aWR0aDogMTcwcHg7CiAgaGVpZ2h0OiAxNzBweDsKICBtYXJnaW4tdG9wOiAwOwpib3JkZXI6bm9uZQp9CgoKLmltcG93ZXJCb3ggLnRpdGxlLAouaW1wb3dlckJveCAgLmluZm8gewogIGRpc3BsYXk6IG5vbmU7Cn0KCg=='
    }
  },

  // 监控data中的数据变化
  watch: {
    wxShow: {
      handler(newV,oldV) {
        this.dialogVisible = this.wxShow
        if (newV) {
          this.getRandom()
          this.getweixinURL()
          this.isBindWeixin()
          this.time = setInterval(()=> {
            setTimeout(()=>{
              this.isBindWeixin()
              this.numbers++
            },0)
            if(this.numbers === 59) {
            this.numbers = 0
            this.redirect_uri = ''
            window.localStorage.setItem('character', '')
            clearTimeout(this.time)
          }
          },2000)
        } else {
          clearTimeout(this.time)
          clearInterval(this.time)
        }
      },
      // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
      immediate: true,
      // deep: true,
    }
  },

  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.numbers = 0
  },
  destroyed() {
    clearTimeout(this.time)
  },
  // 方法集合
  methods: {
      async isBindWeixin() {
       let data = {
        wechatLoginUuid: this.character
      }
      let res = await isBindWeixin(data)
      if (res.data.code === 20000) {
        this.$message.closeAll()
        if (res.data.data.type  === 1) {
          setToken(res.data.data.token)
          const userInfo = await this.$store.dispatch('user/getInfo')
          const path = getDefultPath(userInfo.roleName)
          this.$router.replace({
              path
        })
        } else if(res.data.data.type  === 2) {
          this.wxInfo = { ...res.data.data}
          // this.$message.error(res.data.message)
        } else if (res.data.data.type === 4) {
          this.$message.error(res.data.message)
        } else if(res.data.data.type === 3) {
          this.$message.success(res.data.message || '微信绑定成功')
        }
        window.localStorage.setItem("character", '')
        clearTimeout(this.time)
        clearInterval(this.time)
      } else {
        this.wxLoginShow = true
        if(!res.data.data && this.numbers === 59) {
          this.numbers = 0
          this.redirect_uri = ''
          window.localStorage.setItem('character', '')
          clearTimeout(this.time)
          clearInterval(this.time)
        }
      }
    },
    clickTest() {
      this.getRandom()
      this.getweixinURL()
       this.isBindWeixin()
           this.time = setInterval(()=> {
            setTimeout(()=>{
              this.isBindWeixin()
              this.numbers++
            },0)
            if(this.numbers === 59) {
            clearTimeout(this.time)
             clearInterval(this.time)
            this.numbers = 0
            this.redirect_uri = ''
          }
          },2000)
    },
    // 获取随机32位
    getRandom() {
      let len = 32;
      let chars ='ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
      let maxPos = chars.length;
      let character = '';
      for (let i = 0; i < len; i++) {
        character += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      window.localStorage.setItem('character', character)
      this.character = character
    },
    // 微信URL
    async getweixinURL() {
      // this.isShow = false
      let data = {
        type: this.$route.path === '/login' ? 1 : 2,
        wechatLoginUuid: this.character
      }
      let res = await weixinURL(data)
      if(res.data.code === 20000) {
        this.redirect_uri = res.data.data.redirect_uri
        this.appid = res.data.data.appid
        this.scope = res.data.data.scope
        this.state = res.data.data.state
      } else {
        this.$message.error(res.data.$message)
      }
    },
    handleColse() {
      this.$emit('update:wxShow', false)
    },
    getRegister(index) {
      this.$emit('setRegister', index)
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类

  .wx-login {
    ::v-deep .el-dialog {
      margin-top: 0 !important;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -46%);
      background: url(../../../assets/images/login/wx-bg.png) no-repeat;
      background-size: cover;
      box-shadow: none;
      width: 300px;
      height: 355px;

      .el-dialog__header {
        border: none;
        font-size: 16px;

        .el-icon-close {
          /* font-size: 32px; */
          font-weight: 700;
          color: #333333;

        }
      }

      .line-box {
        margin: 0 auto;
        width: 240px;
        height: 36px;
        overflow: hidden;
        position: relative;
        margin-bottom: 28px;

        .line-info {
          position: absolute;
          width: 600px;
          bottom: 0;
          left: -12px;
          top: 7px;
          span {
            display: inline-block;
            width: 14px;
            height: 1px;
            background-color: #d9d9d9;
            margin: 0 4px;
          }
        }
      }
    }

    .wx-tips {
      text-align: center;
      font-size: 14px;
      // line-height: 32px;
      margin-top: -8px;
    }

  }

  .Codelogin {
    margin: 0 auto;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 168px;
    height: 168px;
    background: #f2f2f2;
    border-radius: 2px;
    /* border: 2px solid #eee; */

    ::v-deep iframe {
      width: 170px;
      height: 170px;
      margin: 0 auto;
    }
  }
</style>
